package com.kehutong.admin.service;

import java.util.List;

import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

import com.kehutong.admin.entity.db.CorpDatabase;

@WebService("/admin/service/database")
public class CorpDatabaseService {
	
	@Inject
	private JdbcSession jdbcSession;

	@ReqMapping("/get")
	public Object get(String companyNo) {
		CorpDatabase terminal = jdbcSession.findOne(CorpDatabase.class)
				.eq("companyNo", companyNo)
				.eq("deleted", false)
	    		.exe();
		
		if (Objects.isNull(terminal)) {
			return Result.error(1001, "database not exist in companyNo=" + companyNo);
		}
		
		return toJSON(terminal);
	}
	
	private JSONObject toJSON(CorpDatabase db) {
		JSONObject jsonObject = new JSONObject(6);
		jsonObject.put("companyNo", db.getCompanyNo());
		jsonObject.put("sourceClassName", db.getSourceClassName());
		jsonObject.put("url", db.getUrl());
		jsonObject.put("username", db.getUsername());
		jsonObject.put("password", db.getPassword());
		jsonObject.put("minimumSize", db.getMinimumSize());
		jsonObject.put("maximumSize", db.getMaximumSize());
		jsonObject.put("acquireIncrement", db.getAcquireIncrement());
		jsonObject.put("acquireRetryDelay", db.getAcquireRetryDelay());
		
		return jsonObject;
	}
	
	public CorpDatabase getDB(String companyNo) {
		CorpDatabase terminal = jdbcSession.findOne(CorpDatabase.class)
				.eq("companyNo", companyNo)
				.eq("deleted", false)
				.exe();
		
		return terminal;
	}
	
	public List<CorpDatabase> getDBList() {
		return jdbcSession.findArray(CorpDatabase.class)
				.eq("deleted", false)
	    		.exe();
	}

	public List<CorpDatabase> getDBList(String corpId) {
		return jdbcSession.findArray(CorpDatabase.class)
				.eq("id", corpId)
				.eq("deleted", false)
				.exe();
	}
}
